package com.yaowk.system.controller;

import com.feizhou.swagger.annotation.Api;
import com.feizhou.swagger.annotation.ApiOperation;
import com.feizhou.swagger.annotation.Param;
import com.feizhou.swagger.annotation.Params;
import com.jfinal.log.Log;
import com.yaowk.common.constant.ServiceCode;
import com.yaowk.common.controller.BaseController;
import com.yaowk.common.kit.I18nKit;
import com.yaowk.system.common.Constant;
import com.yaowk.system.model.Menu;
import com.yaowk.system.model.User;
import com.yaowk.system.shiro.TokenKit;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import java.util.List;

/**
 * 用户认证接口
 *
 * @authc yaowk
 * 2017/7/5
 */
@Api(tag = "auth", description = "认证", url = "/system/auth")
public class AuthController extends BaseController {

    @ApiOperation(url = "/login", httpMethod = "post", description = "登录")
    @Params({
            @Param(name = "username", description = "用户名", required = true),
            @Param(name = "password", description = "密码", required = true)
    })
    public void login() {
        User user = getBean(User.class, "");
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        try {
            subject.login(usernamePasswordToken);
        } catch (IncorrectCredentialsException e) {
            Log.getLog("").info("", e);
            renderFail(ServiceCode.FAIL, I18nKit.get("username_or_password_mistake", Constant.MODULE_NAME, this));
            return;
        }
        renderJson(TokenKit.getUserInfo());
    }

    @ApiOperation(url = "/menuList", description = "获取用户的菜单和按钮", tag = "auth")
    public void menuList() {
        List<Menu> menus = Menu.dao.findMenuByUserId(TokenKit.getUserId());
        menus = Menu.dao.parseMenu(menus);
        renderJson(menus);
    }

    @ApiOperation(url = "/logout", description = "登出系统")
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        renderSuccess();
    }

    public void unauthorizedUrl() {
        Log.getLog("").info("unauthorizedUrl");
        renderFail(ServiceCode.NO_PERMISSION, I18nKit.get("unauthorized", Constant.MODULE_NAME, this));
    }

    public void successUrl() {
        renderSuccess();
    }

    public void loginUrl() {
        renderFail(ServiceCode.NO_LOGIN, I18nKit.get("no_login", Constant.MODULE_NAME, this));
    }
}
